import axios from 'axios'
import Vue from 'vue'

const RNTY_BASE_URL = 'http://192.168.3.13:9001/'
const RNTY_AUTH_BASE_URL = 'http://192.168.3.13:9000/'
const CLIENT_ID = 3
const CLIENT_SECRET = 'LObGcz7I1YcTC4Ze7wczr4ACmf81uLDY'
const _this = Vue.prototype

function authLogin() {
  request({
    method: 'post',
    baseURL: RNTY_AUTH_BASE_URL,
    url: 'clients/authentication',
    data: {
      client_id: CLIENT_ID,
      client_secret: CLIENT_SECRET,
      redirect_url: window.location.href
    }
  }).then(({data: {auth_code, login_url}}) => {
    console.log(auth_code)
    _this.$cookie.set('auth_code', auth_code, '')
    window.location.href = login_url;
    return false
  })
}

function tokenRequest({method = 'get', baseURL, url, param, data}) {
  let token = _this.$cookie.get('rnty_access_token')
  if (!token) {
    authLogin()
    return
  }
  axios.defaults.baseURL = baseURL
  axios.defaults.transformRequest = [function (data) {
    // Do whatever you want to transform the data
    let ret = ''
    for (let it in data) {
      ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
    }
    return ret
  }]
  axios.defaults.withCredentials = true
  axios.defaults.headers.common['Authorization'] = `Bearer ${token}`
  axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
  return axios({
    method: method,
    url: url,
    param: param
  }).catch((error) => {
    if (error.response.status === 401) {
      authLogin()
    }
  })
}

function request({method = 'get', baseURL, url, param = null, data = null}) {
  axios.defaults.baseURL = baseURL
  axios.defaults.transformRequest = [function (data) {
    // Do whatever you want to transform the data
    let ret = ''
    for (let it in data) {
      ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
    }
    return ret
  }]
  axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

  return axios({
    method: method,
    url: url,
    param: param,
    data: data
  })
}

export default {
  RNTY_BASE_URL,
  RNTY_AUTH_BASE_URL,
  CLIENT_ID,
  CLIENT_SECRET,
  tokenRequest,
  request,
  authLogin
}
